{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "40f73521",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "同余方程组的解为 x ≡ 23 (mod 105)\n"
     ]
    }
   ],
   "source": [
    "def extended_gcd(a, b):\n",
    "    if b == 0:\n",
    "        return a, 1, 0\n",
    "    else:\n",
    "        d, x, y = extended_gcd(b, a % b)\n",
    "        return d, y, x - (a // b) * y\n",
    "\n",
    "def chinese_remainder_theorem(congruences):\n",
    "    \"\"\"\n",
    "    中国剩余定理求解函数\n",
    "\n",
    "    :param congruences: 模线性同余方程组，格式为 [(a1, m1), (a2, m2), ..., (an, mn)]，表示方程组为 x ≡ ai (mod mi)\n",
    "    :return: 方程组的解 x\n",
    "    \"\"\"\n",
    "    # 计算模数的乘积 M\n",
    "    M = 1\n",
    "    for _, mi in congruences:\n",
    "        M *= mi\n",
    "\n",
    "    # 计算 Mi 和 Mi 的模逆元素\n",
    "    M_values = [M // mi for _, mi in congruences]\n",
    "    Mi_values = [extended_gcd(Mi, mi)[1] for Mi, (_, mi) in zip(M_values, congruences)]\n",
    "\n",
    "    # 计算解 x\n",
    "    x = sum(ai * Mi * mi for (ai, _), Mi, mi in zip(congruences, Mi_values, M_values)) % M\n",
    "\n",
    "    return x\n",
    "\n",
    "# 示例：解 x ≡ 2 (mod 3), x ≡ 3 (mod 5), x ≡ 2 (mod 7)\n",
    "congruences = [(2, 3), (3, 5), (2, 7)]\n",
    "solution = chinese_remainder_theorem(congruences)\n",
    "print(f\"同余方程组的解为 x ≡ {solution} (mod {congruences[0][1] * congruences[1][1] * congruences[2][1]})\")\n",
    "# 同余方程组的解为 x ≡ 23 (mod 105)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f3af462",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
